/**
  ******************************************************************************
  * @file           
  * @author         东方电科
  * @brief          iec104 应用文件
  ******************************************************************************
  *
  * COPYRIGHT(c) 2019 GoodMorning
  *
  ******************************************************************************
  */

/* Includes -----------------------------------------------------------------*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include <unistd.h>
#include <signal.h>
#include <sys/time.h>   //select time

#include "iec10x.h"
#include "unixsock.h"

/* Private types ------------------------------------------------------------*/

/* Private macro ------------------------------------------------------------*/


#define VERSION "V1.0.11"

/** @name   宏定义转字符串
  * @brief  如 MACRO2STR(arg1,arg2) 则生成字符串 "arg1,arg2" ;
  * @{
*/
#define MACRO2STR_(...)   #__VA_ARGS__  
#define MACRO2STR(...)    MACRO2STR_(__VA_ARGS__)
/** @}*/

/// 是否定时更新转发表
#define UPDATE_TRANS_TABLE 0



/* Private variables --------------------------------------------------------*/

static int unixsock = 0;
struct iec10x demobus = {0};

/* Global  variables --------------------------------------------------------*/

/* Private function prototypes ----------------------------------------------*/

/* Gorgeous Split-line ------------------------------------------------------*/







static void iec104_puts(uint8_t * info , int len)
{
	if (unixsock) {
		write(unixsock , info , len);
	}
}



void * iec104_poll(void *arg)
{
	size_t time = 0;
	struct timeval timer100ms ;
	while( 1 ) {
		timer100ms.tv_sec = 0;
		timer100ms.tv_usec = 50000 ;
		select(0, NULL, NULL, NULL, &timer100ms);
		time += 50 ;
		// 处理协议栈 100ms 超时/定时任务，此处不需要太精确
		iec10x_periodic_handle(time); 
	}
}



void * iec104_recv(void *arg)
{
	unsigned char databuf[1024];
	int readn;
	while( 1 ) {
		readn = read(unixsock,databuf,sizeof(databuf));
		if (readn < 1) {
			printf("recv error.exit.\r\n");
			close(unixsock);
			exit(1);
		}
		iec10x_recv(&demobus,databuf,readn);
	}
}





int main(int argc, char *argv[])
{
	pthread_t newthread;
	struct iec104cfg cfg = {0};

	unixsock = unix_socket_connect("m104f",NULL);
	if (unixsock < 0) {
		printf("cannot connect to m104f\r\n");
		return -1;
	}

	iec10x_protocol_init();
	
	cfg.haltx    = iec104_puts ;
	cfg.print    = printf      ;
	cfg.dbglevel = 2           ;
	cfg.mode     = 0           ;
	iec10x_bus_init(&demobus,104,&cfg,NULL);

	pthread_create(&newthread,NULL,iec104_poll  ,NULL);
	pthread_create(&newthread,NULL,iec104_recv  ,NULL);

	iec10x_change_dir(&demobus,"iecrecv");
	printf("iec104 file service slave.\r\n");

	getchar();
	return 0;
}
